package com.example.listen;



import com.example.bean.DeviceFullInfo;
import com.example.bean.DeviceInfo;
import com.example.bean.DevicePara;
import com.example.bean.NetInfo;
import com.example.service.CLibrary;
import com.example.util.ByteUtil;
import com.example.util.EStringUtil;
import com.example.util.TypeConversionUtil;
import com.fazecast.jSerialComm.SerialPortTimeoutException;
import com.sun.jna.ptr.ByteByReference;
import com.sun.jna.ptr.IntByReference;
import org.springframework.stereotype.Component;
import com.fazecast.jSerialComm.SerialPort;

import javax.xml.bind.DatatypeConverter;
import java.io.InputStream;

@Component
public class ComServer {

    public static void main(String[] args) {
        // 指定串口号和波特率
        String portName = "COM3";  // 根据需要修改为指定的串口号
        int baudRate = 115200;       // 根据需要修改为指定的波特率
        // 获取指定的串口
        byte Baudrate = TypeConversionUtil.intTobyte(baudRate);
        IntByReference hComm = new IntByReference();
        IntByReference reference = CLibrary.INSTANCE.OpenDevice(hComm, portName, new ByteByReference(Baudrate));
        String data = TypeConversionUtil.typeConversion(reference);
        if(data!=null  || hComm.getValue() == 0){
            System.out.println("获取设备信息失败");
            return;
        }
        NetInfo info = new NetInfo();
        CLibrary.INSTANCE.GetNetInfo(hComm.getValue(), info);
        String mac = ByteUtil.byteToMacAddressString(info.getMAC());
        System.out.println("mac地址:"+mac);
        DeviceFullInfo deviceFullInfo=new DeviceFullInfo();
        CLibrary.INSTANCE.GetDeviceInfo( hComm.getValue(),deviceFullInfo);
        System.out.println("SN地址:"+DatatypeConverter.printHexBinary(deviceFullInfo.getDeviceSN()));
        if (hComm.getValue() != 0) {
            try {
                System.out.println("关闭机器");
                CLibrary.INSTANCE.CloseDevice(hComm.getValue());
            } catch (Error e) {
                e.printStackTrace();
            }
        }
        SerialPort serialPort = SerialPort.getCommPort(portName);
        if (serialPort == null) {
            System.out.println("串口 " + portName + " 不存在或无法访问！");
            return;
        }
        try {
            // 打开串口
            if (!serialPort.openPort()) {
                System.out.println("无法打开串口 " + portName);
                return;
            }
            // 设置串口参数：波特率、数据位、停止位、校验位
            serialPort.setBaudRate(baudRate);  // 设置波特率
            serialPort.setNumDataBits(12);      // 设置数据位为 12 位
            serialPort.setNumStopBits(1);      // 设置停止位为 1
            serialPort.setParity(SerialPort.NO_PARITY);  // 无校验位
            serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING,300,0);
            // 获取串口的输入流
            InputStream inputStream = serialPort.getInputStream();

            // 创建一个缓冲区来存储读取到的数据
            byte[] readBuffer = new byte[1024];
            int numBytes;

            System.out.println("正在读取串口数据...");
            int i=0;
            // 持续读取串口数据
            while (true) {
                // 读取数据
                try{
                    if ((numBytes = inputStream.read(readBuffer)) > 0) {
                        byte[] readByte = new byte[numBytes];
                        System.arraycopy(readBuffer, 0, readByte, 0, numBytes);
                        String cardInfo = DatatypeConverter.printHexBinary(readByte);
                        cardInfo= EStringUtil.convertHexToString(cardInfo);
                        System.out.println("读取到的数据:"+cardInfo+",mac地址:"+mac);
                    }else {
                        // 如果没有数据读取，休眠一段时间（避免CPU占用过高）
                        Thread.sleep(100);
                    }
                }catch (SerialPortTimeoutException e){
                    //e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭串口
            if (serialPort.isOpen()) {
                serialPort.closePort();
                System.out.println("串口已关闭");
            }
        }
    }

    /*@PostConstruct
    public void readCardInfo() {
        CompletableFuture.runAsync(()->{
            try {
                // 获取所有可用的串口端口
                Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
                while (portList.hasMoreElements()) {
                    CommPortIdentifier portId = portList.nextElement();
                    System.out.println("Available Port: " + portId.getName());
                }

                // 假设我们使用第一个串口端口
                String portName = "COM1";  // 替换为你需要使用的串口号

                // 打开串口
                CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName);
                CommPort commPort = portId.open(ComServer.class.getName(), 2000);

                if (commPort instanceof SerialPort) {
                    SerialPort serialPort = (SerialPort) commPort;

                    // 设置串口参数：波特率，数据位，停止位，校验位
                    serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                    // 获取输入流
                    InputStream inputStream = serialPort.getInputStream();

                    // 添加串口数据监听
                    serialPort.addEventListener(new SerialPortEventListener() {
                        @Override
                        public void serialEvent(SerialPortEvent event) {
                            if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                                try {
                                    // 如果有数据可用，读取数据
                                    int availableBytes = inputStream.available();
                                    byte[] buffer = new byte[availableBytes];
                                    inputStream.read(buffer);
                                    System.out.println("Received Data: " + new String(buffer));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                    serialPort.notifyOnDataAvailable(true);

                    // 让程序持续运行，等待数据到达
                    System.out.println("Waiting for data...");
                    while (true) {
                        // 让主线程保持运行状态，持续监听串口数据
                        Thread.sleep(1000);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }*/
}
